<template>
  <div class="scales-manage">
    <div class="table-header">
      <div class="left">
        <el-input
          v-model="searchQuery"
          placeholder="搜索量表名称"
          style="width: 200px"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增量表
      </el-button>
    </div>

    <!-- 量表列表 -->
    <el-table
      v-loading="loading"
      :data="scaleList"
      border
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="量表名称" />
      <el-table-column prop="type" label="量表类型" />
      <el-table-column prop="targetAge" label="适用年龄" />
      <el-table-column prop="totalScore" label="总分" width="80" />
      <el-table-column prop="estimatedTime" label="预计用时">
        <template #default="{ row }">
          {{ row.estimatedTime }}分钟
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="未启用"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ row.createdAt ? new Date(row.createdAt).toLocaleString() : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="success" link @click="handleQuestions(row)">
            题目管理
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 量表表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增量表' : '编辑量表'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="scaleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="量表名称" prop="name">
          <el-input v-model="scaleForm.name" placeholder="请输入量表名称" />
        </el-form-item>
        <el-form-item label="量表类型" prop="type">
          <el-select v-model="scaleForm.type" placeholder="请选择量表类型" style="width: 100%">
            <el-option label="抑郁量表" value="抑郁量表" />
            <el-option label="焦虑量表" value="焦虑量表" />
            <el-option label="压力量表" value="压力量表" />
            <el-option label="人格测试" value="人格测试" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="适用年龄" prop="targetAge">
          <el-input v-model="scaleForm.targetAge" placeholder="例如：18-60岁" />
        </el-form-item>
        <el-form-item label="总分" prop="totalScore">
          <el-input-number v-model="scaleForm.totalScore" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="预计用时" prop="estimatedTime">
          <el-input-number 
            v-model="scaleForm.estimatedTime" 
            :min="1" 
            style="width: 100%"
          >
            <template #suffix>分钟</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="scaleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入量表描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import request from '../../../utils/request'

const router = useRouter()
const loading = ref(false)
const scaleList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

const scaleForm = ref({
  name: '',
  type: '',
  targetAge: '',
  totalScore: 0,
  estimatedTime: 30,
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入量表名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择量表类型', trigger: 'change' }
  ],
  targetAge: [
    { required: true, message: '请输入适用年龄', trigger: 'blur' }
  ],
  totalScore: [
    { required: true, message: '请输入总分', trigger: 'blur' }
  ],
  estimatedTime: [
    { required: true, message: '请输入预计用时', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入量表描述', trigger: 'blur' },
    { max: 500, message: '长度不能超过 500 个字符', trigger: 'blur' }
  ],
}

// 获取量表列表
const fetchScales = async () => {
  loading.value = true
  try {
    const res = await request.get('/admin/scales', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        query: searchQuery.value
      }
    })
    scaleList.value = res.records
    total.value = res.total
    currentPage.value = res.current
    pageSize.value = res.size
  } catch (error) {
    console.error('获取量表列表错误:', error)
    ElMessage.error('获取量表列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchScales()
}

// 新增量表
const handleAdd = () => {
  dialogType.value = 'add'
  scaleForm.value = {
    name: '',
    type: '',
    targetAge: '',
    totalScore: 0,
    estimatedTime: 30,
    description: ''
  }
  dialogVisible.value = true
}

// 编辑量表
const handleEdit = (row) => {
  dialogType.value = 'edit'
  scaleForm.value = {
    id: row.id,
    name: row.name,
    type: row.type,
    targetAge: row.targetAge,
    totalScore: row.totalScore,
    estimatedTime: row.estimatedTime,
    description: row.description
  }
  dialogVisible.value = true
}

// 删除量表
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该量表吗？', '提示', {
      type: 'warning'
    })
    await request.delete(`/admin/scales/${row.id}`)
    ElMessage.success('删除成功')
    fetchScales()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 题目管理
const handleQuestions = (row) => {
  // 跳转到题目管理页面
  router.push(`/admin/scales/${row.id}/questions`)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await request.post('/admin/scales', scaleForm.value)
          ElMessage.success('添加成功')
        } else {
          await request.put(`/admin/scales/${scaleForm.value.id}`, scaleForm.value)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchScales()
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchScales()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchScales()
}

// 添加 handleStatusChange 函数
const handleStatusChange = async (row) => {
  try {
  const res=  await request.put(`/admin/scales/status/${row.id}?status=${row.status}`, {
    })
    if(res.code===200){
      ElMessage.success('状态更新成功')
    }else{
      row.status = row.status === 1 ? 0 : 1
      ElMessage.error(res.message)
    }
  } catch (error) {
    // 如果更新失败，恢复原来的状态
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

onMounted(() => {
  fetchScales()
})
</script>

<style scoped>
.scales-manage {
  padding: 20px;
}

.table-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  display: flex;
  gap: 15px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style> 